<?php
	session_start();

	function getIpAddress(){
	  if (!empty($_SERVER['HTTP_CLIENT_IP'])){
		$ip=$_SERVER['HTTP_CLIENT_IP'];
	  }
	  elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])){
		$ip=$_SERVER['HTTP_X_FORWARDED_FOR'];
	  }
	  else{
		$ip=$_SERVER['REMOTE_ADDR'];
	  }
	  return $ip;
	}

	function checkLogin(){
		if(!isset($_SESSION["login_id"])){
			header("Location: /cms/login.php");
		}
	}

	function generateRandomString($length = 10) {    
		return substr(str_shuffle("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"), 0, $length);
	}
	
	function encrypt_string($value){
		$value = base64_encode(generateRandomString(2)."|".$value."|".generateRandomString(2));
		$result = base64_encode(generateRandomString(4).$value.generateRandomString(4));
		return $result;
	}
	
	function decrypt_string($value){
		$result = base64_decode($value);
		$result = mb_substr($result, 4, -4);
		$result = base64_decode($result);
		
		$result = explode("|", $result);
		
		return $result[1];
	}
	
	function calculate_total($type, $discount, $data_list){
	
		$total = 0;
		$PriceList = "";
		$dicount = explode(",", $discount);
		
		switch ($type) {
			case "A":
				foreach ($data_list as &$product) {
					$total += $product[1]*$product[2];
					$total = $total * ($discount[0]/100);
				}
				
				break;
				
			case "B":
				$buy = $discount[0];
				$free = $discount[1];
				
				$PriceList = "";
				foreach ($data_list as &$product) {
					for($i=0;$i<$product[1];$i++){
						array_push($PriceList, $product[2]);
					}
				}

				if(count($PriceList) >= $discount[0]){
					$x = ceil($buy*$total_amount/($buy+$free));

					$PriceList = arsort($PriceList);
					
					for ($i = 0;$i < $x;$i++) {
						$total += $PriceList[$i];
					}
				}
				else{
					foreach ($data_list as &$product) {
						$total += $product[1]*$product[2];
					}
				}
				
				break;
				
			case "C":
				if (count($data_list) >= $discount[0]){
					foreach ($data_list as &$product) {
						$total += $product[1]*$product[2];
						$total = $total * ($discount[0]/100);
					}
				}
				else{
					foreach ($data_list as &$product) {
						$total += $product[1]*$product[2];
					}
				}
				break;
			default:
				foreach ($data_list as &$product) {
					$total += $product[1]*$product[2];
				}
				break;
		}
		
		return total;
	}
?>